package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.DaoBlog;
import dao.DaoUser;
import dao.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //约定前后端交互
        //编写后端代码
        //编写前端代码

        //1.判断是不是详情页,除了详情页都是登陆者自己
        //2.只有详情页有blogId
        if(req.getParameter("blogId") == null){

            //返回登陆者自己
            HttpSession session = req.getSession();
            User user = null;
            //如果session为空或者user对象为空就创建新的user对象
            if(session == null ||(user = (User) session.getAttribute("user"))== null) {
                user = new User();
            }
            //最后把无论是新创建的user对象还是已经存在的user对象都传回去
            String responseString = objectMapper.writeValueAsString(user);
            resp.setContentType("application/json; charset=utf8");
            resp.setStatus(200);
            resp.getWriter().write(responseString);

        }else {
            //返回该篇文章的作者信息
            DaoBlog daoBlog = new DaoBlog();
            //获取这篇博客的信息
            Blog blog = daoBlog.getBlogById(Integer.parseInt(req.getParameter("blogId")));
            User user = null;
            //如果该博客不存在,如果该博客存在
            if(blog == null){
                //不存在就创建一个新的用户
                 user = new User();
            }else {
                //存在就返回这个博客的作者
                 user = DaoUser.getUserById(blog.getUserId());
            }
            //通过博客信息里面包含的用户id,来查找这个用户的详细信息
            //转换成json格式
            String responseString = objectMapper.writeValueAsString(user);
            resp.setContentType("application/json; charset=utf8");
            resp.setStatus(200);
            resp.getWriter().write(responseString);

        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
